package com.ruoyi.dm.component;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import com.ruoyi.common.constant.CollectFileTypeConstants;
import com.ruoyi.common.utils.biz.BizModule;
import com.ruoyi.common.utils.biz.PathUtil;
import com.ruoyi.dm.domain.po.SpaceEnvCollectRecordPO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.input.ReversedLinesFileReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

/**
 * 空间 环境观测指数  太阳辐射观测,地磁辐射指数
 */
@Component
@Slf4j
public class SunDataStrategy implements DataStrategy<SpaceEnvCollectRecordPO> {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public SpaceEnvCollectRecordPO makeupPo(SpaceEnvCollectRecordPO po) {
        String fullPath = PathUtil.outputModuleDir(BizModule.COLLECT)+po.getFilePath();
        File path = new File(fullPath, po.getFileName());
        ReversedLinesFileReader reader = null;
        try {
            reader = ReversedLinesFileReader.builder().setFile(path).get();
            String line = "";
            while (null != (line=reader.readLine())) {
                // 截取最新数据时间
                // 2023-05-05	118.9
                if (StringUtils.hasLength(line)) {
                    String str =  line.substring(0,10);
                    po.setFileDate(DateUtil.parse(str,"yyyy-MM-dd"));
                    break;
                }
            }
        } catch (IOException e) {
            log.error("解析时间异常",e);
        }

        return po;
    }

    @Override
    public String pythonCmd(String satellite, String dataType, String filePath,String method, Integer year) {
        String fileType = CollectFileTypeConstants.TYPE_SUN;
        //只有一个算法
        String outPath = PathUtil.outputModuleDir(BizModule.COLLECT) + PathUtil.moduleDirs().getCollect().get("result") + "/" + fileType ;
        FileUtil.mkdir(outPath);
        String logPath = PathUtil.tmpModuleDir(BizModule.COLLECT) + PathUtil.moduleDirs().getCollect().get("result") + "/" + fileType;
        FileUtil.mkdir(logPath);
        String script = PathUtil.codeModuleDir(BizModule.COLLECT) + PathUtil.moduleDirs().getCollect().get("sunScript");
        String[] cmdLines = new String[10];
        cmdLines[0] = "python";
        cmdLines[1] = script;
        cmdLines[2] = "--filepath";//原始文件
        cmdLines[3] = filePath;
        cmdLines[4] = "--outfile";//产品路径
        cmdLines[5] = outPath;
        cmdLines[6] = "--outlog";//日志路径
        cmdLines[7] = logPath;
        cmdLines[8] = "--inter_type";//评估结果路径
        cmdLines[9] = outPath;
        String commond = ArrayUtil.join(cmdLines, " ");
        log.info("拼接脚本:{}", commond);
        return commond;
    }


    @Override
    public void save(String dataType, String outFile) throws IOException, Exception {
        //将数据保存到  SWDATA_OBS_xxx 里
        log.info("开始执行数据入库....{},{}",dataType,outFile);
        String tableName = "SWDATA_OBS_"+dataType.toUpperCase();
        BufferedReader reader = new BufferedReader(new FileReader(outFile));
        //首行忽略
        reader.readLine();
        String line = "";
        //先查询数据库最新数据
        Date date = jdbcTemplate.queryForObject("select max(\"DATETIME\") FROM " + tableName, Date.class);
        ArrayList list = new ArrayList();
        while (null != (line = reader.readLine())) {
            //2015-12-16	-37
            String[] split = line.split("\t|,");
            //DateTime parse = DateUtil.parse(split[0], "yyyy-MM-dd");
            //if (date ==null || parse.isAfter(date)) {
            //    //,只录入超过最新数据的时间
                list.add(new String[]{split[0],split[1]});
            //}
        }
        log.info("新增数据....{},{}",dataType,list.size());
        switch (dataType.toUpperCase()) {
            case "F107":
                jdbcTemplate.batchUpdate("insert into "+tableName+"(\"DATETIME\",\"F107\") values(?,?)",list);
                break;
            case "Y107":
                jdbcTemplate.batchUpdate("insert into "+tableName+"(\"DATETIME\",\"Y107\") values(?,?)",list);
                break;
            case "M107":
                jdbcTemplate.batchUpdate("insert into "+tableName+"(\"DATETIME\",\"M107\") values(?,?)",list);
                break;
            case "S107":
                jdbcTemplate.batchUpdate("insert into "+tableName+"(\"DATETIME\",\"S107\") values(?,?)",list);
                break;
            case "E107":
                jdbcTemplate.batchUpdate("insert into "+tableName+"(\"DATETIME\",\"e107\") values(?,?)",list);
                break;
        }
    }
}
